<template>
  <div class="course-detail-container">
    <FrontendHeader />
    
    <!-- 课程基本信息 -->
    <div class="course-header">
      <div class="container">
        <div class="course-main-info">
          <div class="course-preview">
            <img v-if="course.image" :src="course.image" :alt="course.name" class="course-image">
          </div>
          <div class="course-details">
            <h1>{{ course.name }}</h1>
            <div class="course-meta">
              <span class="course-type">{{ courseType }}</span>
              <span class="course-students">{{ course.students || 0 }}人学习</span>
              <span class="course-date">{{ course.createTime }}</span>
            </div>
            <div class="course-price">¥{{ course.price }}</div>
            <div class="course-actions">
              <el-button type="primary" size="large" @click="handleBuyCourse" v-if="!isPurchased">立即购买</el-button>
              <el-button type="success" size="large" @click="handleStartLearning" v-else>开始学习</el-button>
              <el-button size="large" @click="handleAddToCart">加入收藏</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 选项卡内容 -->
    <div class="course-tabs-section">
      <div class="container">
        <div class="course-content">
          <!-- 选项卡导航 -->
          <el-tabs v-model="activeTab" class="custom-tabs">
            <el-tab-pane label="课程介绍" name="introduction">
            <div class="introduction-content">
              <div class="course-description" v-html="course.detail"></div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="课程章节" name="chapters">
            <div class="chapters-content">
              <div v-if="chapters.length > 0">
                <el-collapse v-model="activeChapters" class="custom-collapse">
                  <el-collapse-item :title="chapter.name" :name="chapter.id" v-for="chapter in chapters" :key="chapter.id">
                    <div class="chapter-sections">
                      <div 
                        class="section-item" 
                        v-for="section in chapter.sections" 
                        :key="section.id"
                        :class="{ 'locked': !isPurchased && !section.free }"
                      >
                        <div class="section-info">
                          <el-icon  class="section-icon"><VideoPlay /></el-icon>
                          <span class="section-title">{{ section.name }}</span>
                          <span class="section-duration" >{{ section.duration }}</span>
                        </div>
                        <div class="section-actions">
                          <span v-if="!isPurchased && !section.free" class="locked-text">购买后观看</span>
                          <el-button 
                            type="text" 
                            @click="handleSectionClick(section)" 
                            v-else
                          >
                            {{ '预览' }}
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
              <div v-else class="no-chapters">
                <p>暂无章节信息</p>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="学员评价" name="reviews">
            <div class="reviews-content">
              <div class="reviews-summary">
                <div class="overall-rating">
                  <div class="rating-score">{{ course.rating || 0 }}</div>
                  <div class="rating-stars">
                    <el-rate :model-value="course.rating || 0" disabled show-score />
                  </div>
                  <div class="rating-count">{{ course.reviewCount || 0 }}条评价</div>
                </div>
                <div class="rating-distribution">
                  <div class="rating-item" v-for="i in 5" :key="i">
                    <span class="rating-number">{{ 6 - i }}星</span>
                    <div class="rating-bar">
                      <div class="rating-progress" :style="{ width: getRatingPercentage(6 - i) + '%' }"></div>
                    </div>
                    <span class="rating-percent">{{ getRatingPercentage(6 - i) }}%</span>
                  </div>
                </div>
              </div>
              
              <div class="reviews-list">
                <div class="review-item" v-for="review in reviews" :key="review.id">
                  <div class="review-header">
                    <div class="review-user">
                      <img :src="review.userAvatar" :alt="review.userName" class="review-avatar">
                      <div class="review-user-info">
                        <span class="review-username">{{ review.userName }}</span>
                        <span class="review-date">{{ review.createTime }}</span>
                      </div>
                    </div>
                    <div class="review-rating">
                      <el-rate :model-value="review.rating" disabled />
                    </div>
                  </div>
                  <div class="review-content">{{ review.content }}</div>
                </div>
              </div>
              
              <div class="pagination">
                <el-pagination
                  v-model:current-page="reviewPagination.currentPage"
                  v-model:page-size="reviewPagination.pageSize"
                  layout="prev, pager, next"
                  :total="reviewPagination.total"
                  @current-change="handleReviewPageChange"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
        </div>
      </div>
    </div>
    <!-- 学习资源 -->
    <div class="learning-resources">
      <div class="container">
        <h2>学习资源</h2>
        <div class="resources-container">
          <div class="resource-card" v-for="resource in learningResources" :key="resource.id">
            <div class="resource-icon">{{ resource.icon }}</div>
            <div class="resource-content">
              <h3>{{ resource.title }}</h3>
              <p>{{ resource.description }}</p>
              <a :href="resource.url" target="_blank" class="resource-link">{{ resource.linkText }}</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 页脚 -->
    <FrontendFooter />
  </div>
</template>

<script setup>
import FrontendHeader from '../../components/FrontendHeader.vue'
import FrontendFooter from '../../components/FrontendFooter.vue'
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { VideoPlay, Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {coursesById} from "@/api/Course.js";
import {queryCourseInOrdersStatus} from "@/api/Payment.js";

const route = useRoute()
const router = useRouter()
//获取路由跳转的时候携带的课程id
const courseId = route.params.id

// 课程数据
const course = ref({
  id: '',
  name: '',
  detail: '',
  image: '',
  price: 0,
  typeId: '',
  students: 0,
  createTime: '',
  rating: 0,
  reviewCount: 0
})

// 课程类型名称
const courseType = ref('')



// 章节数据
const chapters = ref([])
const activeChapters = ref(['1'])

// 评价数据
const reviews = ref([])
const reviewPagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
})

// 学习资源
const learningResources = ref([
  {
    id: 1,
    icon: '📚',
    title: '课程源码与示例',
    description: '包含课程中所有示例代码和项目源码，方便对照学习和实践',
    url: '#',
    linkText: '下载源码'
  },
  {
    id: 2,
    icon: '📝',
    title: '学习笔记模板',
    description: '精心设计的学习笔记模板，帮助整理知识点和记录学习心得',
    url: '#',
    linkText: '获取模板'
  },
  {
    id: 3,
    icon: '🔧',
    title: '开发工具配置',
    description: '课程推荐的开发环境和工具配置指南，提升开发效率',
    url: '#',
    linkText: '查看指南'
  },
  {
    id: 4,
    icon: '🧰',
    title: '扩展学习资料',
    description: '精选的扩展学习资料和参考文档，深入理解核心概念',
    url: '#',
    linkText: '浏览资料'
  }
])

// 选项卡
const activeTab = ref('introduction')

// 是否已购买
const isPurchased = ref(false)

// 获取课程详情
const fetchCourseDetail = () => {
  // 这里应该调用API获取课程详情
  coursesById(courseId).then(res=>{
    course.value = res.data
    console.log(res)
    chapters.value =res.data.chaptersList
  })
  courseType.value = '前端开发'
  // 模拟评价数据
  reviews.value = [
    {
      id: 1,
      userName: '张三',
      userAvatar: 'https://picsum.photos/32/32?random=10',
      rating: 5,
      content: '课程内容非常丰富，讲解清晰，很适合初学者学习。',
      createTime: '2023-07-15'
    },
    {
      id: 2,
      userName: '李四',
      userAvatar: 'https://picsum.photos/32/32?random=11',
      rating: 4,
      content: '老师讲得很好，就是实战项目可以再详细一些。',
      createTime: '2023-07-20'
    }
  ]
  reviewPagination.total = reviews.value.length
  // 检查是否已购买
  // 这里应该根据用户订单信息判断
  const token = sessionStorage.getItem('token')
  const user = sessionStorage.getItem('userInfo')
  if (token) {
    queryCourseInOrdersStatus({
      userId:JSON.parse(user).id,
      courseId:courseId
    }).then(res=>{
      console.log("查看课程购买状态")
      console.log(res)
      if(res.data){
        isPurchased.value = true
      }else{
        isPurchased.value = false
      }
    })

  }
}

// 获取评分百分比（模拟）
const getRatingPercentage = (stars) => {
  const ratings = {
    5: 65,
    4: 25,
    3: 7,
    2: 2,
    1: 1
  }
  return ratings[stars] || 0
}

// 购买课程
const handleBuyCourse = () => {
  //获取用户状态的token
  const token = sessionStorage.getItem('token')
  if (!token) {
    // 显示确认对话框，让用户选择是去登录还是取消
    ElMessageBox.confirm(
      '购买课程需要先登录账号，是否前往登录？',
      '登录提示',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      // 保存当前页面路径，登录后可以跳转回来
      sessionStorage.setItem('redirectAfterLogin', `/course/detail/${courseId}`)
      router.push('/login')
    }).catch(() => {
      // 用户取消登录
    })
    return
  }

  try {
    // 跳转到订单确认页面
    router.push(`/user/orders/create/${courseId}`)
  } catch (error) {
    console.error('跳转到订单页面失败:', error)
    ElMessage.error('创建订单失败，请稍后重试')
  }
}

// 开始学习
const handleStartLearning = () => {
  router.push(`/course/learn/${courseId}`)
}

// 收藏课程
const handleAddToCart = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  ElMessage.success('收藏成功')
}

// 点击章节小节
const handleSectionClick = (section) => {
  if (isPurchased.value || section.free) {
    router.push(`/course/learn/${courseId}?sectionId=${section.id}`)
  }
}

// 评价分页切换
const handleReviewPageChange = (current) => {
  reviewPagination.currentPage = current
  // 这里应该加载对应页的评价数据
}

// 页面加载时获取数据
onMounted(() => {
  fetchCourseDetail()
})
</script>

<style scoped>
.course-detail-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-top: 0;
  padding-bottom: 0;
  display: flex;
  flex-direction: column;
  padding-bottom: 60px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  flex: 1;
}

.course-header {
  background-color: white;
  padding: 30px 0;
  margin-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}

.course-main-info {
  display: flex;
  gap: 30px;
}

.course-preview {
  flex-shrink: 0;
}

.course-image,
.course-video {
  width: 500px;
  height: 280px;
  object-fit: cover;
  border-radius: 8px;
}

.course-details {
  flex: 1;
}

.course-details h1 {
  font-size: 28px;
  margin-bottom: 16px;
  color: #303133;
}

.course-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #606266;
}

.course-type {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 4px;
}

.course-price {
  font-size: 32px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 30px;
}

.course-actions {
  display: flex;
  gap: 16px;
}

.course-tabs-section {
  background-color: white;
  border-top: 1px solid #ebeef5;
}

.course-content {
  background-color: white;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.introduction-content,
.chapters-content,
.reviews-content {
  padding: 0;
}

/* 自定义选项卡样式 */
.custom-tabs .el-tabs__header {
  margin: 0;
  border-bottom: 1px solid #ebeef5;
}

.custom-tabs .el-tabs__nav {
  padding: 0;
}

.custom-tabs .el-tabs__item {
  padding: 15px 32px;
  font-size: 16px;
  color: #606266;
  transition: all 0.3s;
}

.custom-tabs .el-tabs__item:hover {
  color: #667eea;
}

.custom-tabs .el-tabs__item.is-active {
  color: #667eea;
  font-weight: 500;
}

.custom-tabs .el-tabs__active-bar {
  background-color: #667eea;
  height: 3px;
  border-radius: 3px;
}

.introduction-content,
.chapters-content,
.reviews-content {
  padding: 30px 0;
}

.introduction-content h2 {
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
  font-weight: 600;
}

.course-description {
  line-height: 1.6;
  color: #606266;
  margin-bottom: 24px;
  font-size: 16px;
}

.learning-goals,
.suitable-people {
  line-height: 1.6;
  color: #606266;
  margin-bottom: 24px;
  font-size: 16px;
}

.learning-goals li,
.suitable-people li {
  margin-bottom: 10px;
  padding-left: 8px;
}

.chapter-sections {
  padding: 10px 0;
}

.section-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.section-item:hover {
  background-color: #f5f7fa;
}

.section-item.locked {
  opacity: 0.6;
  cursor: not-allowed;
}

.section-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.section-icon {
  color: #667eea;
}

.section-title {
  flex: 1;
  color: #303133;
}

.section-duration {
  color: #909399;
  font-size: 14px;
}

.locked-text {
  color: #f56c6c;
  font-size: 14px;
}

/* 评分相关样式 */
.reviews-summary {
  display: flex;
  gap: 80px;
  margin-bottom: 50px;
  padding-bottom: 40px;
  border-bottom: 1px solid #ebeef5;
  align-items: flex-start;
}

.overall-rating {
  text-align: center;
  flex: 0 0 200px;
}

.rating-score {
  font-size: 72px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 20px;
  line-height: 1;
}

.rating-count {
  color: #909399;
  margin-top: 15px;
  font-size: 16px;
}

.rating-distribution {
  flex: 1;
}

.rating-item {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 15px;
  font-size: 16px;
}

.rating-number {
  width: 60px;
  font-size: 16px;
  color: #606266;
  text-align: right;
}

.rating-bar {
  flex: 1;
  height: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
  overflow: hidden;
}

.rating-progress {
  height: 100%;
  background-color: #f56c6c;
  transition: width 0.3s ease;
}

/* 评价内容样式 */
.review-item {
  padding: 24px 0;
  border-bottom: 1px solid #f0f0f0;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.review-user {
  display: flex;
  align-items: center;
  gap: 12px;
}

.review-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.review-user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.review-username {
  font-weight: 600;
  color: #303133;
}

.review-date {
  color: #909399;
  font-size: 14px;
}

.review-content {
  color: #606266;
  line-height: 1.8;
  font-size: 16px;
}

  .rating-percent {
    width: 60px;
    text-align: right;
    font-size: 16px;
    color: #909399;
  }

  /* 评价列表样式 */
  .review-item {
    padding: 30px 0;
    border-bottom: 1px solid #ebeef5;
  }

  .review-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .review-user {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .user-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
  }

  .user-name {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
  }

  .review-content {
    line-height: 1.8;
    color: #606266;
    margin-bottom: 15px;
    font-size: 18px;
  }

  .review-date {
    font-size: 16px;
    color: #909399;
  }

  .pagination {
    margin-top: 40px;
    text-align: center;
  }

  /* 学习资源 */
  .learning-resources {
  margin-top: 30px;
  border-top: 1px solid #ebeef5;
  padding: 40px 0;
  background-color: #f8f9fa;
}

.learning-resources h2 {
  font-size: 24px;
  margin-bottom: 30px;
  color: #303133;
  font-weight: 500;
  position: relative;
  padding-bottom: 12px;
}

.learning-resources h2::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 50px;
  height: 3px;
  background-color: #667eea;
  border-radius: 3px;
}

.resources-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.resource-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.resource-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.resource-icon {
  font-size: 36px;
  flex-shrink: 0;
}

.resource-content {
  flex: 1;
}

.resource-content h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #303133;
  font-weight: 500;
}

.resource-content p {
  margin: 0 0 12px 0;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.resource-link {
  display: inline-flex;
  align-items: center;
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  transition: color 0.3s;
}

.resource-link:hover {
  color: #5a67d8;
}

.resource-link::after {
  content: '→';
  margin-left: 4px;
  font-size: 12px;
}
  

/* 响应式设计 */
@media (max-width: 768px) {
  .course-main-info {
    flex-direction: column;
  }
  
  .course-image,
  .course-video {
    width: 100%;
    height: auto;
  }
  
  .course-actions {
    flex-direction: column;
  }
  
  .reviews-summary {
    flex-direction: column;
  }
}

/* 页脚样式 */
.footer {
  background-color: #1f2937;
  color: white;
  padding: 80px 0 40px;
  position: relative;
}

.footer::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2);
}

.footer-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-bottom: 60px;
  gap: 40px;
}

.footer-brand {
  flex: 1;
  min-width: 250px;
  margin-bottom: 30px;
}

.footer-links {
  flex: 1;
  min-width: 200px;
  margin-bottom: 30px;
}

.footer-contact {
  flex: 1;
  min-width: 250px;
  margin-bottom: 30px;
}

.footer-brand .logo {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
}

.footer-brand .logo-icon {
  font-size: 32px;
  color: #667eea;
  margin-right: 10px;
}

.footer-brand .logo-text {
  font-size: 22px;
  font-weight: 700;
  color: white;
}

.footer-brand p {
  color: #9ca3af;
  line-height: 1.7;
  font-size: 15px;
  margin-bottom: 24px;
  max-width: 300px;
}

.footer-links h4,
.footer-contact h4 {
  margin: 0 0 24px 0;
  font-size: 18px;
  font-weight: 600;
  color: white;
  position: relative;
  padding-bottom: 10px;
}

.footer-links h4::after,
.footer-contact h4::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 40px;
  height: 2px;
  background-color: #667eea;
}

.footer-links ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.footer-links li {
  margin-bottom: 12px;
}

.footer-links a {
  color: #9ca3af;
  text-decoration: none;
  font-size: 15px;
  transition: color 0.3s;
}

.footer-links a:hover {
  color: #667eea;
}

.footer-contact p {
  margin: 0 0 16px 0;
  color: #9ca3af;
  font-size: 15px;
  display: flex;
  align-items: center;
}

.footer-contact p::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 6px;
  background-color: #667eea;
  border-radius: 50%;
  margin-right: 12px;
}

.footer-bottom {
  text-align: center;
  padding-top: 30px;
  border-top: 1px solid #374151;
  color: #9ca3af;
  font-size: 15px;
}
</style>